import {
  Component,
  OnInit,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  Input,
  Output,
  EventEmitter,
  ChangeDetectorRef,
  OnChanges,
} from '@angular/core';
import { Subject } from 'rxjs';
import { InputBoolean } from '../core/api';
import { SelectService } from './select.service';

@Component({
  selector: 'lv-option',
  templateUrl: './option.component.html',
  styles: [],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'lv-option lv-select-selection-item',
    '[class.disabled]': 'lvDisabled',
    '[class.selected]': 'lvSelected',
    '[class.lv-option-multiple]': 'multiple',
    '[class.lv-option-hover-disabled]': 'lvHoverDisabled',
    '(click)': 'toggleSelect($event)',
  },
})
export class OptionComponent implements OnInit, OnChanges {
  @Input() lvLabel: string; // 下拉展示内容
  @Input() lvSelected: boolean; // 是否选中
  // 输入输出属性
  @Input() @InputBoolean() lvDisabled = false; // 是否禁用
  @Input() @InputBoolean() lvReadOnly = false; // 是否不可选中
  @Input() @InputBoolean() lvHoverDisabled = false; // 不允许鼠标hover样式，仅内部使用

  @Output() lvSelectedChange = new EventEmitter<boolean>(); // 选中状态变更事件回调

  clear: boolean = false; // 标识，单选时判断是不是外部触发清除
  // 外部可访问变量
  multiple: boolean = false;
  toggleSelected$ = new Subject<boolean>();

  // 内部变量
  constructor(
    private selectService: SelectService,
    private _cdr: ChangeDetectorRef,
  ) {
    this.multiple = this.selectService.isMultipleMode();
  }

  ngOnInit(): void {}

  ngOnChanges(): void {}

  /**
   * 切换选中
   * 不可更改场景：
   * 1. disabled
   * 单选模式下，已被选中在选中不修改状态
   */
  toggleSelect(e: MouseEvent = null): void {
    e?.stopPropagation();
    // 1
    if (this.lvDisabled || this.lvReadOnly) {
      return;
    }

    if (this.multiple || !this.lvSelected) {
      this.lvSelected = !this.lvSelected;
    }

    this.lvSelectedChange.emit(this.lvSelected);
  }
}
